import React, { Fragment, useEffect, useState } from 'react';
import { ColumnProps, PaginationConfig, SorterResult } from 'antd/es/table';
import { UserItem } from './data';
import { Button, Card, Divider, message, Modal, Popconfirm, Table, Tag, Upload } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from '@/utils/table.less';
import { ConnectState, Dispatch } from '@/models/connect';
import { connect } from 'dva';
import encodeQueryParam from '@/utils/encodeParam';
import Save from './save';
import Authorization from '@/components/Authorization';
import apis from '@/services';
import SearchForm from '@/components/SearchForm';
import { getAccessToken } from '@/utils/authority';
import { UploadOutlined } from '@ant-design/icons';
import { UploadProps } from "antd/lib/upload";

interface Props{
    users: any;
    dispatch: Dispatch;
    location: Location;
    loading: boolean;
}

interface State {
    data: any;
    searchParam: any;
    saveVisible: boolean;
    currentItem: Partial<UserItem>;
    autzVisible: boolean;
}

const UserList: React.FC<Props> = props => {

    const { dispatch } = props;
    const { result } = props.users;
    const [organizationList, setOrganizationList] = useState([]);

    const initState: State = {
        data: result,
        searchParam: { 
            pageIndex: 0,
            pageSize: 10
        },
        saveVisible: false,
        currentItem: {},
        autzVisible: false,
    };

    const [searchParam, setSearchParam] = useState(initState.searchParam);
    const [saveVisible, setSaveVisible] = useState(initState.saveVisible);
    const [currentItem, setCurrentItem] = useState(initState.currentItem);
    const [autzVisible, setAutzVisible] = useState(initState.autzVisible);
    const [loading, setLoading] = useState(false);
    const columns: ColumnProps<UserItem>[] = [
        {
            title: '姓名',
            dataIndex: 'name',
            width: '160px',
        },
        {
            title: '用户名',
            dataIndex: 'username',
            width: '110px',
        },
        {
            title: '权限名称',
            dataIndex: 'roleNamesStr',
            width: '200px',
        },
        {
            title: '所属机构',
            dataIndex: 'tenantName',
            width: '200px',
        },
        {
            title: '岗位名称',
            dataIndex: 'positionName',
            width: '200px',
        },
        {
            title: '班组',
            dataIndex: 'teamName',
            width: '150px',
        },
        {
            title: '手机号码',
            dataIndex: 'phoneNum',
            width: '130px',
        },
        {
            title: '微信号',
            dataIndex: 'wechatNum',
            width: '160px',
        },
        {
            title: '邮箱账号',
            dataIndex: 'mailbox',
            width: '160px',
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: '80px',
            render: text => <Tag color={text === 1 ? '#108ee9' : '#f50'}>{text === 1 ? '正常' : '已禁用'}</Tag>,
        },
        {
            title: '操作',
            align: 'center',
            width: '200px',
            fixed: 'right',
            render: (text, record) => (
                <Fragment>
                    <a onClick={() => edit(record)}>编辑</a>
                    <Divider type="vertical" />

                    <a onClick={() => setting(record)}>赋权</a>
                    <Divider type="vertical" />
                    {record.status !== 1 ? (
                        <span>
                            <Popconfirm
                                title="确认启用此用户？"
                                onConfirm={() => {
                                    enableOrDisable(record);
                                }}
                            >
                                <a>启用</a>
                            </Popconfirm>
                            <Divider type="vertical" />
                            <a onClick={() => handleDelete(record)}>删除</a>
                        </span>
                    ) : (
                            <Popconfirm
                                title="确认禁用此用户？"
                                onConfirm={() => {
                                    enableOrDisable(record);
                                }}
                            >
                                <a>禁用</a>
                            </Popconfirm>
                        )}
                </Fragment>
            ),
        },
    ];

    const handleSearch = (params?: any) => {
        setSearchParam(params);
        dispatch({
            type: 'users/userlist',
            payload: encodeQueryParam(params)
        });
    };
    const template = () =>{
        const formElement = document.createElement('form');
        formElement.style.display = 'display:none;';
        formElement.action = `/AllLinks/用户导入模板.xlsx`;
        document.body.appendChild(formElement);
        formElement.submit();
        document.body.removeChild(formElement);
    };
    const downloadUsersTemplate = () => {
        const formElement = document.createElement('form');
        formElement.style.display = 'display:none;';
        formElement.method = 'get';
        formElement.action = `/AllLinks/user/user_export`;
        // delete searchParam.pageSize;
        // delete searchParam.pageIndex;
        console.log(searchParam)
        if(searchParam.tenantId == undefined){
            searchParam.tenantId = '';
        }
        if(searchParam.phoneNum == undefined){
            searchParam.phoneNum = '';
        }
        if(searchParam.name == undefined){
            searchParam.name = '';
        }
        if(searchParam.useraname == undefined){
            searchParam.username = '';
        }
        const params = encodeQueryParam(searchParam);

        Object.keys(params).forEach((key: string) => {
          const inputElement = document.createElement('input');
          inputElement.type = 'hidden';
          inputElement.name = key;
          inputElement.value = params[key];
          formElement.appendChild(inputElement);
        });
        const inputElement = document.createElement('input');
        inputElement.type = 'hidden';
        inputElement.name = ':X_Access_Token';
        inputElement.value = getAccessToken();
        formElement.appendChild(inputElement);
    
        document.body.appendChild(formElement);
        formElement.submit();
        document.body.removeChild(formElement);
      }; 

    useEffect(() => {
        handleSearch(searchParam);
        apis.users.getOrganization()
            .then((res: any) => {
            if (res.status === 200) {
                let orgList: any = [];
                res.result.map((item: any) => {
                    orgList.push({ id: item.id, pId: item.parentId, value: item.id, title: item.name })
                });
                setOrganizationList(orgList);
            }
            }).catch(() => {
        });
    }, []);

    const enableOrDisable = (record: UserItem) => {
        apis.users.saveOrUpdate(
            { id: record.id, status: record.status === 1 ? 0 : 1 }
        ).then(res => {
            if (res.status === 200) {
                if (record.status === 1) {
                    message.success("禁用成功");
                } else {
                    message.success("启用成功");
                }
                handleSearch(searchParam);
            } else {
                message.error(`操作失败，${res.message}`)
            }
        }
        ).catch(() => { });
    };


    const edit = (record: UserItem) => {
        getById(record.id);
    };
    const getById = (id:string) =>{
        dispatch({
            type: 'users/queryById',
            payload: id,
            callback: (response: any) => {
                if (response.status === 200) {
                    setCurrentItem(response.result);
                    setSaveVisible(true);
                } 
            }
        })
    };
    const setting = (record: UserItem) => {
        setAutzVisible(true);
        setCurrentItem(record);
    };

    const saveOrUpdates = (user: UserItem) => {
        dispatch({
            type: 'users/formSave',
            payload: encodeQueryParam(user),
            callback: (response: any) => {
                if (response.status === 200) {
                    message.success("添加成功");
                    setSaveVisible(false);
                    handleSearch(searchParam);
                    setCurrentItem({})
                } else {
                    // message.error(`添加失败，${response.message}`);
                }
            }
        })
    };
    const handleDelete = (params: any) => {
        Modal.confirm({
            title: '确定删除此用户吗？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                dispatch({
                    type: 'users/remove',
                    payload: params.id,
                    callback: response => {
                        if (response.status === 200) {
                            message.success("删除成功");
                            handleSearch(searchParam);
                        } else {
                            message.error("删除失败");
                        }
                    }
                });
            },
        })
    };
    const uploadProps: UploadProps = {
        action: '/AllLinks/file/static',
        headers: {
            'X-Access-Token': getAccessToken(),
        },
        showUploadList: false,  
        onChange(info) {
            if (info.file.status === 'uploading') {
                setLoading(true);
            }
            if (info.file.status === 'done') {
                // message.success('上传成功');
                upSubmit(info.file.response.result)
                setLoading(false);
            }
        },
    };
    const upSubmit = (file:string) => {
        dispatch({
            type: 'users/upload',
            payload: file,
            callback: (response: any) => {
                if (response.status === 200) {
                    message.success("导入成功");
                    handleSearch(searchParam);
                }else{
                    message.error(response.message);
                }
            }
        })
    };

    const onTableChange = (pagination: PaginationConfig, filters: any, sorter: SorterResult<any>, extra: any) => {
        handleSearch({
            pageIndex: Number(pagination.current) - 1,
            pageSize: pagination.pageSize,
            terms: searchParam,
            sorts: sorter,
        });
    };
    const conditions = (params: any) =>{
        if(params){
            handleSearch(params);
        }else{
            let list:any = [];
            list.pageSize = 10;
            list.pageIndex = 0;
            handleSearch(list);
        }
    };

    return (
        <PageHeaderWrapper title="用户管理">
            <Card bordered={false}>
                <div className={styles.tableList}>
                    <div>
                        <SearchForm
                            search={(params: any) => {
                                // setSearchParam(params);
                                conditions(params)
                            }}
                            formItems={[
                                {
                                    label: "所属机构",
                                    key: "tenantId",
                                    type: 'treeSelect',
                                    props: {
                                        data: organizationList,
                                        dropdownStyle: {maxHeight: 500}
                                      }
                                },
                                {
                                    label: "姓名",
                                    key: "name",
                                    type: 'string'
                                },
                                {
                                    label: "用户名",
                                    key: "username",
                                    type: 'string'
                                },
                                {
                                    label: "手机号码",
                                    key: "phoneNum",
                                    type: 'string'
                                },
                                
                            ]}
                        />
                    </div>
                    <div className={styles.tableListOperator}>
                        <Button icon="plus" type="primary" onClick={()=>{ setSaveVisible(true) }}>新建</Button>
                        <Upload {...uploadProps} showUploadList={false}>
                            <div className={styles.button_view}>
                                <Button>
                                    <UploadOutlined />导入
                                </Button>
                            </div>
                        </Upload>
                        <Button icon="download" type="default" onClick={() => { downloadUsersTemplate() }}>导出</Button>
                        <Button type="dashed" onClick={() => { template() }}>下载模版</Button>
                    </div>
                    <div className={styles.StandardTable}>
                        <Table
                            loading={props.loading}
                            dataSource={(result || {}).data}
                            columns={columns}
                            scroll={{ x: 1300 }}
                            rowKey="id"
                            onChange={onTableChange}
                            pagination={{
                                current: result.pageIndex + 1,
                                total: result.total,
                                pageSize: result.pageSize,
                                showQuickJumper: true,
                                showSizeChanger: true,
                                pageSizeOptions: ['10', '20', '50', '100'],
                                showTotal: (total: number) => `共 ${total} 条记录 第  ${result.pageIndex + 1}/${Math.ceil(result.total / result.pageSize)}页`
                            }}
                        />
                    </div>
                </div>
            </Card>
            {
                saveVisible &&
                <Save
                    data={currentItem}
                    close={() => { setSaveVisible(false); setCurrentItem({}) }}
                    save={(user: UserItem) => { saveOrUpdates(user) }}
                />
            }
            {
                autzVisible &&
                <Authorization
                    close={() => { setAutzVisible(false); setCurrentItem({}) }}
                    target={currentItem}
                    targetType='user'
                />
            }
        </PageHeaderWrapper>
    )
};
export default connect(({ users, loading }: ConnectState) => ({
    users,
    loading: loading.models.users
}))(UserList)
